﻿/*
LICENCE___________________________________________________________________
    Copyright (C) 2012 Reverdy Sylvain

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License along
    with this program; if not, write to the Free Software Foundation, Inc.,
    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
FIN LICENCE______________________________________________________________
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;


using Merise_designer.Methodes;
using Microsoft.Win32;
using System.IO;
using System.Reflection;


namespace Merise_designer
{
    /// <summary>
    /// Logique d'interaction pour MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {

        public MainWindow()
        {
            InitializeComponent();

            //Ouverture depuis un fichier
            try
            {
                string[] cmdLine = Environment.GetCommandLineArgs();
                if (cmdLine.Count() > 0 && cmdLine[1] != "")
                {
                    fileNameOpenned = cmdLine[1];
                }
            }
            catch { }
        }

        #region attributs
        String fileNameOpenned = ""; //Fichier qui a ouver le programme depuis l'explorer
        private ObjetsCommun mesObjets; //Collection de tous les objets
        private List<Control> child = new List<Control>(); //Utilisé pour les opération à 1 seule sélection et sélection multiple
        private Control childEnt1; //**Utilisés pour les opérations,
        private Control childEnt2; //à 2 sélections,
        private Control childAsso; //selon la fonction à déclancher **
        private Point _MousePosition; //Contient la position souris avant opération (déplacement)
        private bool _MouseDown; //Indique l'état du bouton
        private const int MOVE_RESIZE = 1;
        private const int MOVE_DEPLACEMENT = 2;
        private const int MOVE_NONE = 0;
        private int _moveMode = MOVE_NONE;
        private Boolean _multiModeSelection = false;

        #endregion

        #region chargement
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            mainWindow.PreviewKeyDown += new KeyEventHandler(events_KeyDown);
            mainWindow.PreviewKeyUp += new KeyEventHandler(events_KeyUp);

            myScroll.PreviewMouseWheel += Zoom_Dezoom;
            Grille_Principale.PreviewMouseDown += MiddleMouseDown;
            activate_MouseButtonDown();

            this.Title = "Merise Designer - " + Openroject.getActualProjectFIle() + " *";

            //créé la liste d'objets communs
            mesObjets = new ObjetsCommun(this, Grille_Principale, statusBar);

            //Initialise le fichier de base de données, si échec : quitter application
            if (!mesObjets.prepareNewBDD()) return;

            //Efface les anciennes données de la base interne
            mesObjets.EraseAll(Grille_Principale, true);

            //charge le menu principal
            chargeMenuPrincipal();

            //charge les éléments
            mesObjets.reLoadBackUp();
            mesObjets.backup.checkOnLoad();
            mesObjets.CreateBackUpFIle(); //Pour les opérations Annuler/Rétablir

            mesObjets.LoadingBDD(Grille_Principale);
            Openroject.isSaved = true;

            if (fileNameOpenned != "") this.OpenDocument(fileNameOpenned, false);
            fileNameOpenned = "";

            tg_operationsSuccessives.IsChecked = Configuration.mode_action_enchainees;
        }
        #endregion

        #region Deplacements Redimentionnements
        private void activate_MouseButtonDown()
        {
            Grille_Principale.Cursor = Cursors.Arrow;
            Grille_Principale.MouseLeftButtonDown -= new MouseButtonEventHandler(Grille_Principale_MouseLeftButtonDown);
            Grille_Principale.MouseLeftButtonDown += new MouseButtonEventHandler(Grille_Principale_MouseLeftButtonDown);
        }
        private void desactivate_MouseButtonDown()
        {
            Grille_Principale.Cursor = Cursors.Arrow;
            Grille_Principale.MouseLeftButtonDown -= new MouseButtonEventHandler(Grille_Principale_MouseLeftButtonDown);
        }
        void Grille_Principale_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {

            //récupère l'élément à manipuler
            Control new_Child = CL_Graphique.GetActiveUIElement(e.GetPosition(sender as UIElement), Grille_Principale.Children);

            if (new_Child == null && !_multiModeSelection)
            {
                child.Clear();
                lostFocusAll(); //Déselection
            }
            else if (!_multiModeSelection && child.Count < 2)
            {
                child.Clear();
                lostFocusAll(); //Déselection
            }

            //Ajout à la selection
            if (!child.Contains(new_Child) && new_Child != null)
            {
                child.Add(new_Child);
            }

            else if (child.Contains(new_Child) && new_Child != null && _multiModeSelection)//Retire de la selection
            {
                mesObjets.lostFocus(new_Child.Name);
                child.Remove(new_Child);
            }


            if (child.Count > 0 && child.First() != null && new_Child != null)
            {
                //mémorise les états de souris
                _MousePosition = e.GetPosition(sender as UIElement);
                _MouseDown = true;

                //donne le focus à la sélection
                foreach (Control c in child)
                {
                    mesObjets.lostFocus(c.Name);
                    mesObjets.getFocus(c.Name);
                }

                activate_move_resize();
            }
            else //Selection rectangulaire
            {
                // Mémorise le point de départ de ce rectangle élastique.
                _MousePosition = e.GetPosition(sender as UIElement);
                // La valeur spéciale indique qu'il n'y a pas
                _MouseDown = true;
                activate_move_resize_rectangular();
            }
        }
        private void activate_move_resize()
        {
            //unloadEvents();
            //Autorise les évènements
            Grille_Principale.MouseMove += new MouseEventHandler(DragBar_MouseMove);
            Grille_Principale.MouseLeftButtonUp += new MouseButtonEventHandler(DragBar_MouseLeftButtonUp);
            Grille_Principale.Cursor = Cursors.SizeAll;
            lockMenu();
        }
        private void desactivate_move_resize()
        {
            //Supprimer les évènements
            Grille_Principale.MouseMove -= new MouseEventHandler(DragBar_MouseMove);
            Grille_Principale.MouseLeftButtonUp -= new MouseButtonEventHandler(DragBar_MouseLeftButtonUp);
            activate_MouseButtonDown();
            unLockMenu();
        }
        void DragBar_MouseMove(object sender, MouseEventArgs e)
        {

            if (_MouseDown)
            {
                //Récupère la position actuelle de la souris
                Point cursor = e.GetPosition(sender as UIElement);
                //Selectionne le mode DEPLACEMENT/REDIMENTIONNEMENT
                if (_moveMode == MOVE_NONE)
                {
                    if (mesObjets.getIDpoignee(child.First().Name, cursor) == 3)
                    {
                        _moveMode = MOVE_RESIZE;
                    }
                    else
                    {
                        _moveMode = MOVE_DEPLACEMENT;
                    }
                    if (_multiModeSelection) _moveMode = MOVE_DEPLACEMENT;//En cas de multiselection, on force le mode déplacement
                }

                cursor = Tools.SnapPointToGrid(cursor, Configuration.stepGrid);

                if (_moveMode == MOVE_RESIZE) //Redimentionnement
                {
                    Grille_Principale.Cursor = Cursors.SizeNWSE;

                    mesObjets.movePoignee(child.First().Name, cursor);
                }
                else if (_moveMode == MOVE_DEPLACEMENT) //Déplacement
                {
                    if (cursor != Tools.SnapPointToGrid(_MousePosition, Configuration.stepGrid))
                    {
                        foreach (Control c in child)
                        {
                            mesObjets.move(c.Name, _MousePosition, cursor);
                        }
                        _MousePosition = cursor;
                    }
                }
            }
        }
        void DragBar_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {

            _MouseDown = false; //fin du mouse douwn
            _moveMode = MOVE_NONE; //Fin du move
            _MousePosition = e.GetPosition(sender as UIElement);

            //enregistre la position
            foreach (Control c in child)
            {
                mesObjets.saveUpdate(c.Name);
            }

            if (!_multiModeSelection)
            {
                //child.Clear();
            }
            mesObjets.CreateBackUpFIle(); //Pour les opérations Annuler/Rétablir
            desactivate_move_resize();
        }
        Rectangle rc;
        private void activate_move_resize_rectangular()
        {
            unloadEvents();
            //Autorise les évènements
            Grille_Principale.MouseMove += new MouseEventHandler(MouseMove_Rectangular);
            Grille_Principale.MouseLeftButtonUp += new MouseButtonEventHandler(MouseLeftButtonUp_Rectangular);
            // Grille_Principale.Cursor = Cursors.ScrollAll;
            lockMenu();

            rc = new Rectangle();
            rc.Stroke = System.Windows.Media.Brushes.Black;
            System.Windows.Media.DoubleCollection pointilles = new System.Windows.Media.DoubleCollection();
            pointilles.Add(5);
            pointilles.Add(2);
            rc.StrokeDashArray = pointilles;
            rc.Width = 0; rc.Height = 0;
            rc.HorizontalAlignment = HorizontalAlignment.Left;
            rc.VerticalAlignment = VerticalAlignment.Top;

            Grille_Principale.Children.Add(rc);
        }
        private void desactivate_move_resize_rectangular()
        {
            //Supprimer les évènements
            Grille_Principale.MouseMove -= new MouseEventHandler(MouseMove_Rectangular);
            Grille_Principale.MouseLeftButtonUp -= new MouseButtonEventHandler(MouseLeftButtonUp_Rectangular);
            activate_MouseButtonDown();
            unLockMenu();

            Grille_Principale.Children.Remove(rc);
        }
        void MouseMove_Rectangular(object sender, MouseEventArgs e)
        {
            Point ptCurrent = e.GetPosition((UIElement)sender); ;
            if (_MouseDown)
            {

                MyDrawReversibleRectangle(_MousePosition, ptCurrent);

                List<Control> new_Childs = CL_Graphique.GetActiveUIElement(rc, Grille_Principale.Children);
                foreach (Control c in new_Childs)
                {
                    if (!child.Contains(c) && c != null)
                    {
                        child.Add(c);
                        mesObjets.getFocus(c.Name);
                    }
                }
            }
        }
        // Dessine le cadre
        private void MyDrawReversibleRectangle(Point p1, Point p2)
        {
            Point p = new Point();
            // Standardise le rectangle.
            if (p1.X < p2.X)
            {
                p.X = p1.X;
                rc.Width = (p2.X - p1.X);
            }
            else
            {
                p.X = p2.X;
                rc.Width = (p1.X - p2.X);
            }
            if (p1.Y < p2.Y)
            {
                p.Y = p1.Y;
                rc.Height = (p2.Y - p1.Y);
            }
            else
            {
                p.Y = p2.Y;
                rc.Height = (p1.Y - p2.Y);
            }

            ThicknessConverter myThicknessConverter = new ThicknessConverter();
            Thickness th1 = (Thickness)myThicknessConverter.ConvertFromString(p.X + " " + p.Y + " 0 0");
            rc.Margin = th1;
        }
        void MouseLeftButtonUp_Rectangular(object sender, MouseButtonEventArgs e)
        {
            _MouseDown = false; //fin du mouse douwn
            _moveMode = MOVE_NONE; //Fin du move
            _MousePosition = e.GetPosition(sender as UIElement);
            mesObjets.CreateBackUpFIle(); //Pour les opérations Annuler/Rétablir
            desactivate_move_resize_rectangular();
        }

        #endregion

        #region Créer Entité
        private void activate_addEntite()
        {
            unloadEvents();
            statusBar.Content = "Ajout entite => cliquer à l'emplacement d'insertion";

            //Enlève les focus
            lostFocusAll();

            //Retire les évênements de base et implément les spécialisés
            Grille_Principale.PreviewMouseLeftButtonDown += new MouseButtonEventHandler(MainWindow_MouseLeftButtonDown);
            Grille_Principale.Cursor = Cursors.Cross;
            tg_addEntite.IsChecked = true;
            lockMenu();
        }
        private void desactivate_addEntite()
        {
            //Remet les évênements de base
            Grille_Principale.PreviewMouseLeftButtonDown -= new MouseButtonEventHandler(MainWindow_MouseLeftButtonDown);
            activate_MouseButtonDown();
            Grille_Principale.Cursor = Cursors.Arrow;
            tg_addEntite.IsChecked = false;
            statusBar.Content = "Choisissez une opération";
            unLockMenu();

        }
        void MainWindow_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            //Ajoute l'entité à la position du click
            Point p1 = e.GetPosition(Grille_Principale);
            Point p = Tools.SnapPointToGrid(p1, Configuration.stepGrid);
            mesObjets.AddEntite(p);
            mesObjets.CreateBackUpFIle(); //Pour les opérations Annuler/Rétablir
            if (!Configuration.mode_action_enchainees) desactivate_addEntite();
        }
        #endregion

        #region Supprimer
        private void activate_Delete()
        {
            unloadEvents();
            // Grille_Principale.PreviewMouseLeftButtonDown += new MouseButtonEventHandler(Grille_Principale_MouseLeftButtonDown_delete);
            // Grille_Principale.Cursor = Cursors.No;
            // tg_Delete.IsChecked = true;
            lockMenu();

            //supprime l'objet
            if (child != null && child.Count > 0)
            {
                if (MessageBox.Show("Confirmer la Supression ?", "Supprimer", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                {
                    foreach (Control c in child)
                    {
                        if (c != null)
                        {
                            mesObjets.lostFocus(c.Name);
                            mesObjets.Del(c.Name);
                        }
                    }
                    desactivate_Delete();
                }
            }
            desactivate_Delete();
        }
        private void desactivate_Delete()
        {
            //Grille_Principale.PreviewMouseLeftButtonDown -= new MouseButtonEventHandler(Grille_Principale_MouseLeftButtonDown_delete);
            activate_MouseButtonDown();
            //Grille_Principale.Cursor = Cursors.Arrow;
            //tg_Delete.IsChecked = false;
            unLockMenu();

        }
        void Grille_Principale_MouseLeftButtonDown_delete(object sender, MouseButtonEventArgs e)
        {
            if (!_multiModeSelection) { child.Clear(); lostFocusAll(); }
            Control new_Child = CL_Graphique.GetActiveUIElement(e.GetPosition(Grille_Principale), Grille_Principale.Children);

            if (!child.Contains(new_Child) && new_Child != null)
            {
                child.Add(new_Child);
            }

            //donne le focus à la sélection
            foreach (Control c in child)
            {
                mesObjets.lostFocus(c.Name);
                mesObjets.getFocus(c.Name);
            }


            //supprime l'objet
            if (child.First() != null)
            {
                if (MessageBox.Show("Confirmer la Supression ?", "Supprimer", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                {
                    foreach (Control c in child)
                    {
                        mesObjets.Del(c.Name);
                        mesObjets.CreateBackUpFIle();
                    }
                    desactivate_Delete();
                }
            }
        }

        #endregion

        #region Ajouter une ligne
        private void activate_AddLine()
        {
            unloadEvents();
            statusBar.Content = "Ajout ligne (Entite<->Association) => cliquer sur l'élément source";

            //Enlève les focus
            lostFocusAll();

            //initialise les variables
            childEnt1 = null;
            childAsso = null;

            Grille_Principale.PreviewMouseLeftButtonDown += new MouseButtonEventHandler(Grille_Principale_MouseLeftButtonDown_drawLine);
            Grille_Principale.Cursor = Cursors.Cross;
            tg_AddLine.IsChecked = true;
            lockMenu();
        }
        private void desactivate_AddLine()
        {
            //Remet les évênements de base
            Grille_Principale.PreviewMouseLeftButtonDown -= new MouseButtonEventHandler(Grille_Principale_MouseLeftButtonDown_drawLine);
            activate_MouseButtonDown();
            Grille_Principale.Cursor = Cursors.Arrow;
            statusBar.Content = "Choisissez une opération";
            tg_AddLine.IsChecked = false;
            unLockMenu();
        }
        void Grille_Principale_MouseLeftButtonDown_drawLine(object sender, MouseButtonEventArgs e)
        {
            //récupère l'élément à manipuler
            child.Clear();
            child.Add(CL_Graphique.GetActiveUIElement(e.GetPosition(Grille_Principale), Grille_Principale.Children));

            if (child.First() == null) { return; }

            statusBar.Content = "Ajout ligne (Entite<->Association) => cliquer sur l'élément de destination";

            //mémorise 1 Entité et 1 Association sélectionnés
            if (mesObjets.getTypeOfControl(child.First().Name) == 0 & this.childEnt1 == null)
            {
                this.childEnt1 = child.First();
                mesObjets.getFocus(child.First().Name);
            }
            else if (mesObjets.getTypeOfControl(child.First().Name) == 1 & this.childAsso == null)
            {
                this.childAsso = child.First();
                mesObjets.getFocus(child.First().Name);
            }

            //Vérifie la sélection
            if (childEnt1 != null & childAsso != null)
            {
                //mémorise les états de souris
                _MousePosition = e.GetPosition(sender as UIElement);
                _MouseDown = true;

                //évite de recréer ube ligne existante
                if (mesObjets.IsLineOf(mesObjets.getEntite(childEnt1.Name), mesObjets.getAssociation(childAsso.Name)) == false)
                {
                    //créé la ligne
                    mesObjets.AddLigne(mesObjets.getEntite(childEnt1.Name), mesObjets.getAssociation(childAsso.Name));
                    mesObjets.CreateBackUpFIle(); //Pour les opérations Annuler/Rétablir
                }

                //enlève le focus 
                mesObjets.lostFocus(childEnt1.Name);
                mesObjets.lostFocus(childAsso.Name);
                statusBar.Content = "Ajout ligne (Entite<->Association) => cliquer sur l'élément source";

                childEnt1 = null; childEnt2 = null; childAsso = null;

                if (!Configuration.mode_action_enchainees) desactivate_AddLine();
            }
        }
        #endregion

        #region Ajouter Association
        private void activate_AddAsso()
        {
            unloadEvents();
            statusBar.Content = "Ajout association (Entite<->Entite) => cliquer sur l'entité source";

            //Enlève les focus
            lostFocusAll();

            //initialise les variables
            childEnt1 = null;
            childEnt2 = null;

            Grille_Principale.PreviewMouseLeftButtonDown += new MouseButtonEventHandler(Grille_Principale_MouseLeftButtonDown_addAssociation);
            Grille_Principale.Cursor = Cursors.Cross;
            tg_AddAsso.IsChecked = true;
            lockMenu();
        }
        private void desactivate_AddAsso()
        {
            //Remet les évênements de base
            Grille_Principale.PreviewMouseLeftButtonDown -= new MouseButtonEventHandler(Grille_Principale_MouseLeftButtonDown_addAssociation);
            activate_MouseButtonDown();
            Grille_Principale.Cursor = Cursors.Arrow;
            statusBar.Content = "Choisissez une opération";
            tg_AddAsso.IsChecked = false;
            unLockMenu();
        }
        void Grille_Principale_MouseLeftButtonDown_addAssociation(object sender, MouseButtonEventArgs e)
        {

            //récupère l'élément à manipuler
            child.Clear();
            child.Add(CL_Graphique.GetActiveUIElement(e.GetPosition(Grille_Principale), Grille_Principale.Children));

            //exit de la fonction si aucun objet sélectionné
            if (child.First() == null) { return; }
            statusBar.Content = "Ajout association (Entite<->Entite) => cliquer sur l'entité de destination";
            //mémorise 2 Entités différentes
            if (mesObjets.getTypeOfControl(child.First().Name) == 0 & this.childEnt1 == null)
            {
                this.childEnt1 = child.First();
                mesObjets.getFocus(child.First().Name);
            }
            else if (mesObjets.getTypeOfControl(child.First().Name) == 0 & this.childEnt2 == null)
            {
                this.childEnt2 = child.First();
                mesObjets.getFocus(child.First().Name);
            }

            if (childEnt1 == childEnt2)
            {
                childEnt1 = null;
                statusBar.Content = "Ajout association (Entite<->Entite) => cliquer sur l'entité source";
            }

            //Vérifie la sélection
            if (childEnt1 != null & childEnt2 != null)
            {
                //mémorise les états de souris
                _MousePosition = e.GetPosition(sender as UIElement);
                _MouseDown = true;

                //Get les coordonnées se trouvant au centre des sélection (milieu de Entité1 et ENtité2)
                Point pt = new Point((mesObjets.posLeft(childEnt1.Name) + mesObjets.posLeft(childEnt2.Name)) / 2, (mesObjets.posTop(childEnt1.Name) + mesObjets.posTop(childEnt2.Name)) / 2);

                //Ajoute l'association au point milieu
                mesObjets.AddAssociation(Tools.SnapPointToGrid(pt, Configuration.stepGrid));

                //créé la ligne 1 (Entité1-----Asso et 2(Asso------Entité2)
                mesObjets.AddLigne(mesObjets.getEntite(childEnt1.Name), mesObjets.getLastAssociation());
                mesObjets.AddLigne(mesObjets.getEntite(childEnt2.Name), mesObjets.getLastAssociation());

                //enlève le focus 
                mesObjets.lostFocus(childEnt1.Name);
                mesObjets.lostFocus(childEnt2.Name);

                mesObjets.CreateBackUpFIle(); //Pour les opérations Annuler/Rétablir

                childEnt1 = null; childEnt2 = null;
                statusBar.Content = "Ajout association (Entite<->Entite) => cliquer sur l'entité source";
                if (!Configuration.mode_action_enchainees) desactivate_AddAsso();
            }
        }
        #endregion

        #region Convertions Entite<=>Asso
        private void activate_convert_EntityToAsso()
        {
            unloadEvents();
            statusBar.Content = "Convertion Entite en Association => cliquer sur l'entité à convertir";

            //Enlève les focus
            lostFocusAll();

            //initialise les variables
            child.Clear();

            Grille_Principale.PreviewMouseLeftButtonDown += new MouseButtonEventHandler(Grille_Principale_MouseLeftButtonDown_Convert_entityToAsso);
            Grille_Principale.Cursor = Cursors.Cross;
            tg_convert_entityToAsso.IsChecked = true;
            lockMenu();


        }
        private void desactivate_convert_EntityToAsso()
        {
            //Remet les évênements de base
            Grille_Principale.PreviewMouseLeftButtonDown -= new MouseButtonEventHandler(Grille_Principale_MouseLeftButtonDown_Convert_entityToAsso);
            activate_MouseButtonDown();
            Grille_Principale.Cursor = Cursors.Arrow;
            statusBar.Content = "Choisissez une opération";
            tg_convert_entityToAsso.IsChecked = false;
            unLockMenu();
        }
        void Grille_Principale_MouseLeftButtonDown_Convert_entityToAsso(object sender, MouseButtonEventArgs e)
        {
            //récupère l'élément à manipuler
            child.Clear();
            child.Add(CL_Graphique.GetActiveUIElement(e.GetPosition(Grille_Principale), Grille_Principale.Children));

            if (child.First() == null) { return; }

            //vérifie que c'est une entité
            if (mesObjets.getTypeOfControl(child.First().Name) == 0)
            {
                mesObjets.getFocus(child.First().Name);
                mesObjets.convertToAssociation(mesObjets.getEntite(child.First().Name));

                //if (!Configuration.mode_action_enchainees) 
                desactivate_convert_EntityToAsso();
            }
        }
        private void activate_convert_AssoToEntity()
        {
            unloadEvents();
            statusBar.Content = "Convertion Association en Entité => cliquer sur l'association à convertir";

            //Enlève les focus
            lostFocusAll();

            //initialise les variables
            child.Clear();

            Grille_Principale.PreviewMouseLeftButtonDown += new MouseButtonEventHandler(Grille_Principale_MouseLeftButtonDown_Convert_AssoToEntity);
            Grille_Principale.Cursor = Cursors.Cross;
            tg_convert_AssoToEntity.IsChecked = true;
            lockMenu();


        }
        private void desactivate_convert_AssoToEntity()
        {
            //Remet les évênements de base
            Grille_Principale.PreviewMouseLeftButtonDown -= new MouseButtonEventHandler(Grille_Principale_MouseLeftButtonDown_Convert_AssoToEntity);
            activate_MouseButtonDown();
            Grille_Principale.Cursor = Cursors.Arrow;
            statusBar.Content = "Choisissez une opération";
            tg_convert_AssoToEntity.IsChecked = false;
            unLockMenu();
        }
        void Grille_Principale_MouseLeftButtonDown_Convert_AssoToEntity(object sender, MouseButtonEventArgs e)
        {
            //récupère l'élément à manipuler
            child.Clear();
            child.Add(CL_Graphique.GetActiveUIElement(e.GetPosition(Grille_Principale), Grille_Principale.Children));

            if (child.First() == null) { return; }

            //vérifie que c'est une entité
            if (mesObjets.getTypeOfControl(child.First().Name) == 1)
            {
                mesObjets.getFocus(child.First().Name);
                mesObjets.convertToEntity(mesObjets.getAssociation(child.First().Name));

                //if (!Configuration.mode_action_enchainees) 
                desactivate_convert_AssoToEntity();
            }
        }
        #endregion

        #region Edit
        private void activate_Edit(Boolean manual)
        {
            unloadEvents();
            statusBar.Content = "Edition (Entité-Asso) => cliquer sur l'élément à éditer";

            //Enlève les focus
            // lostFocusAll();

            //Retire les évênements de base et implément les spécialisés
            if (!manual)
            {
                Grille_Principale.PreviewMouseLeftButtonDown -= new MouseButtonEventHandler(MouseLeftButtonDown_Edit);
                Grille_Principale.PreviewMouseLeftButtonDown += new MouseButtonEventHandler(MouseLeftButtonDown_Edit);
                Grille_Principale.Cursor = Cursors.Pen;
                tg_Editer.IsChecked = true;
                lockMenu();
            }
            else
            {
                direct_Edit();
            }
        }
        private void desactivate_Edit()
        {
            //Remet les évênements de base
            Grille_Principale.PreviewMouseLeftButtonDown -= new MouseButtonEventHandler(MouseLeftButtonDown_Edit);
            activate_MouseButtonDown();
            Grille_Principale.Cursor = Cursors.Arrow;
            tg_Editer.IsChecked = false;
            statusBar.Content = "Choisissez une opération";
            unLockMenu();
        }
        void MouseLeftButtonDown_Edit(object sender, MouseButtonEventArgs e)
        {
            //child.Clear();
            //récupère l'élément à manipuler
            Control new_Child = CL_Graphique.GetActiveUIElement(e.GetPosition(sender as UIElement), Grille_Principale.Children);

            if (new_Child == null) { return; }

            //vérifie que c'est une entité ou une association
            if (mesObjets.getTypeOfControl(new_Child.Name) == 0 || mesObjets.getTypeOfControl(new_Child.Name) == 1)
            {
                mesObjets.edit(new_Child.Name);
                if (!Configuration.mode_action_enchainees) desactivate_Edit();
            }

        }
        void direct_Edit()
        {
            if (child != null && child.Count > 0 && child.First() != null)
            {
                //vérifie que c'est une entité ou une association
                if (mesObjets.getTypeOfControl(child.First().Name) == 0 || mesObjets.getTypeOfControl(child.First().Name) == 1)
                {
                    Control c = new Control();
                    c = child.First();
                    child.Clear();
                    mesObjets.getFocus(c.Name);
                    mesObjets.edit(c.Name);
                    desactivate_convert_EntityToAsso();
                }
            }
        }
        #endregion

        #region Menus
        //Menu principal
        private void chargeMenuPrincipal()
        {
            ContextMenu mainMenu = new ContextMenu();
            this.ContextMenu = mainMenu;

            MenuItem item1 = new MenuItem();
            item1.Header = "Ajouter Entité";
            item1.Foreground = Brushes.Black;
            item1.Background = Brushes.Transparent;
            item1.Click += new RoutedEventHandler(menu_AddEntite);
            mainMenu.Items.Add(item1);

            MenuItem item2 = new MenuItem();
            item2.Header = "Ajouter Association";
            item2.Foreground = Brushes.Black;
            item2.Background = Brushes.Transparent;
            item2.Click += new RoutedEventHandler(menu_AddAsso);
            mainMenu.Items.Add(item2);

            MenuItem item3 = new MenuItem();
            item3.Header = "Ajouter Ligne";
            item3.Foreground = Brushes.Black;
            item3.Background = Brushes.Transparent;
            item3.Click += new RoutedEventHandler(menu_AddLine);
            mainMenu.Items.Add(item3);

            MenuItem item4 = new MenuItem();
            item4.Header = "Supprimer";
            item4.Foreground = Brushes.Black;
            item4.Background = Brushes.Transparent;
            item4.Click += new RoutedEventHandler(menu_Delete);
            mainMenu.Items.Add(item4);

            /*
            MenuItem item5 = new MenuItem();
            item5.Header = "Redimentionner";
            item5.Foreground = Brushes.Black;
            item5.Background = Brushes.Transparent;
            item5.Click += new RoutedEventHandler(redimentionner);
            mainMenu.Items.Add(item5);
            */
            MenuItem item6 = new MenuItem();
            item6.Header = "Quitter";
            item6.Foreground = Brushes.Black;
            item6.Background = Brushes.Transparent;
            item6.Click += new RoutedEventHandler(actionQuit);
            mainMenu.Items.Add(item6);

        }
        void lockMenu()
        {
            this.ContextMenu.IsEnabled = false;
            this.ContextMenu.Visibility = Visibility.Collapsed;
        }
        void unLockMenu()
        {
            this.ContextMenu.IsEnabled = true;
            this.ContextMenu.Visibility = Visibility.Visible;
        }
        private void menu_AddEntite(object sender, RoutedEventArgs e)
        {
            if (tg_addEntite.IsChecked == false)
            {
                activate_addEntite();
            }
            else
            {
                desactivate_addEntite();
            }
        }
        private void menu_AddAsso(object sender, RoutedEventArgs e)
        {
            if (tg_AddAsso.IsChecked == false)
            {
                activate_AddAsso();
            }
            else
            {
                desactivate_AddAsso();
            }
        }
        private void menu_AddLine(object sender, RoutedEventArgs e)
        {
            if (tg_AddLine.IsChecked == false)
            {
                activate_AddLine();
            }
            else
            {
                desactivate_AddLine();
            }
        }
        private void menu_Delete(object sender, RoutedEventArgs e)
        {
            activate_Delete();
        }
        #endregion

        #region Evênements clavier
        private void events_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Escape)
            {

                lostFocusAll();
                child.Clear();
                unloadEvents();
                activate_MouseButtonDown();
                unLockMenu();
            }
            else
            {
                #region Projet
                //Nouveau
                if ((Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)) && e.Key == Key.N)
                {
                    Image_NewDocument(null, null);
                }
                //Ouvrir
                if ((Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)) && e.Key == Key.O)
                {
                    Image_OpenDocument(null, null);
                }
                //Enregistrer
                if ((Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)) && e.Key == Key.S)
                {
                    Image_Save(null, null);
                }
                //Enregistrer Sous
                if ((Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)) && (Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift)) && e.Key == Key.S)
                {
                    Image_SaveAs(null, null);
                }
                //Print
                if ((Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)) && e.Key == Key.P)
                {
                    Image_Print(null, null);
                }
                //Export
                if ((Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)) && e.Key == Key.E)
                {
                    Image_Export(null, null);
                }
                //MCD/MDL
                if ((Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)) && e.Key == Key.G)
                {
                    Image_ModeMCD_MLD(null, null);
                }
                //Annuler
                if ((Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)) && e.Key == Key.Z)
                {
                    if (mesObjets.backup.asBack()) this.annuler_Click(null, null);
                }
                //Rétablir
                if ((Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)) && e.Key == Key.Y)
                {
                    if (mesObjets.backup.asNext()) this.retablir_Click(null, null);
                }
                #endregion

                #region View
                //Zoom+
                if ((Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)) && e.Key == Key.Add)
                {
                    this.Image_Zoom(null, null);
                }
                //Zoom-
                if ((Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)) && e.Key == Key.Subtract)
                {
                    this.Image_DeZoom(null, null);
                }
                //ZoomAll
                if ((Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)) && e.Key == Key.T)
                {
                    this.Image_ZoomAll(null, null);
                }
                //Naviger
                if ((Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)) && e.Key == Key.D)
                {
                    activate_Nagivation();
                }
                //Selection
                if ((Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)) && e.Key == Key.W)
                {
                    this.nt_selection_Click(null, null);
                }
                #endregion

                #region Draw
                //AddEntite
                if ((Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)) && e.Key == Key.J)
                {
                    activate_addEntite();
                }
                //AddEntite
                if ((Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)) && e.Key == Key.K)
                {
                    activate_AddAsso();
                }
                //AddLine
                if ((Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)) && e.Key == Key.L)
                {
                    activate_AddLine();
                }
                //Suppression
                if (e.Key == Key.Delete)
                {
                    activate_Delete();
                }

                #endregion

                #region Edition
                //Edition
                if (e.Key == Key.Enter)
                {
                    activate_Edit(true);
                }
                //Mode opérations succéssives
                if ((Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)) && e.Key == Key.Q)
                {
                    if (tg_operationsSuccessives.IsChecked == true)
                    {
                        tg_operationsSuccessives.IsChecked = false;
                    }
                    else
                    {
                        tg_operationsSuccessives.IsChecked = true;

                    }
                        this.tg_operationsSuccessives_Click(null, null);
                }
                //Affichage par NOM/CODE
                if ((Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)) && e.Key == Key.H)
                {
                    if (tg_nomCode.IsChecked == true)
                    {
                        tg_nomCode.IsChecked = false;
                    }else
                    {
                        tg_nomCode.IsChecked = true;
                    }
                    this.tg_nomCode_Click(null, null);
                }
                #endregion

                //Déplacements
                #region deplacements flèches
                //gauche
                if (Keyboard.IsKeyDown(Key.Left))
                {
                    //gauche
                    foreach (Control c in child)
                    {
                        mesObjets.move(c.Name, new Point(0, 0), new Point(-Configuration.stepGrid, 0));
                    }
                }
                //droite
                if (Keyboard.IsKeyDown(Key.Right))
                {
                    //droite
                    foreach (Control c in child)
                    {
                        mesObjets.move(c.Name, new Point(0, 0), new Point(Configuration.stepGrid, 0));
                    }
                }
                //haut
                if (Keyboard.IsKeyDown(Key.Up))
                {
                    //haut
                    foreach (Control c in child)
                    {
                        mesObjets.move(c.Name, new Point(0, 0), new Point(0, -Configuration.stepGrid));
                    }
                }
                //bas
                if (Keyboard.IsKeyDown(Key.Down))
                {
                    //bas
                    foreach (Control c in child)
                    {
                        mesObjets.move(c.Name, new Point(0, 0), new Point(0, Configuration.stepGrid));
                    }
                }
                #endregion

                #region Autres

                //Multi selection
                if (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl))
                {
                    _multiModeSelection = true;
                }

                //Selectionner tout
                if ((Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)) && e.Key == Key.A)
                {
                    child.Clear();
                    child.AddRange(mesObjets.selectAll());
                }
                #endregion

            }

        }
        private void events_KeyUp(object sender, KeyEventArgs e)
        {
            //Multi selection
            if (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl))
            {
                _multiModeSelection = true;
            }
            else { _multiModeSelection = false; }

        }

        #endregion

        #region Diverses Méthodes
        private void lostFocusAll()
        {
            if (child.Count > 0 && child.First() != null) { mesObjets.lostFocus(child.First().Name); }
            if (childAsso != null) { mesObjets.lostFocus(childAsso.Name); }
            if (childEnt1 != null) { mesObjets.lostFocus(childEnt1.Name); }
            if (childEnt2 != null) { mesObjets.lostFocus(childEnt2.Name); }
            //Supprime les poignées qui trainent !
            CL_Graphique.ClearPoigneesResiduelles(Grille_Principale);
        }
        void actionQuit(object sender, RoutedEventArgs e)
        {
            Application.Current.Shutdown();
        }
        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            Boolean reponseYes = !Openroject.isSaved && MessageBox.Show("Le présent document n'a pas été enregistré, voulez-vous l'enregistrer ?", "Enregistrement", MessageBoxButton.YesNo) == MessageBoxResult.Yes;
            if (reponseYes)
            {
                Image_Save(null, null);
            }
            mesObjets.backup.removeAll();
        }
        public void unloadEvents()
        {
            desactivate_move_resize();
            desactivate_move_resize_rectangular();
            desactivate_addEntite();
            desactivate_AddAsso();
            desactivate_AddLine();
            desactivate_Delete();
            desactivate_Navigation();
            desactivate_convert_EntityToAsso();
            desactivate_convert_AssoToEntity();
            desactivate_Edit();

            //A laisser en dernière position
            desactivate_MouseButtonDown();

            mainWindow.UpdateLayout();
        }
        private void initGrillePrincipale()
        {
            Grille_Principale.Children.Clear();
            lostFocusAll();
            child.Clear();
        }
        #endregion

        #region Evênements du menu
        //zoom+
        private void Image_Zoom(object sender, MouseButtonEventArgs e)
        {
            Zoom(new Point(0, 0));
        }
        //zoom-
        private void Image_DeZoom(object sender, MouseButtonEventArgs e)
        {
            DeZoom(new Point(0, 0));
        }
        //zoom tout
        private void Image_ZoomAll(object sender, MouseButtonEventArgs e)
        {
            Point center = new Point(myScroll.ScrollableHeight / 2, myScroll.ScrollableWidth / 2);

            //Force l'affichage à l'échelle par défaut
            slider.Value = 1;
            Grille_Principale.LayoutTransform = new ScaleTransform(slider.Value, slider.Value, center.X, center.Y);
            myScroll.UpdateLayout();

            //Dézomm jusqu'à ce que tout le document soit visible
            while (!(myScroll.ScrollableHeight == 0 && myScroll.ScrollableWidth == 0))
            {
                //DeZoom(center);
                slider.Value -= 0.01;
                Grille_Principale.LayoutTransform = new ScaleTransform(slider.Value, slider.Value, center.X, center.Y);
                myScroll.UpdateLayout();
                Console.WriteLine(myScroll.ScrollableHeight + ";" + myScroll.ScrollableWidth);
            }
        }
        //Nouveau document
        private void Image_NewDocument(object sender, MouseButtonEventArgs e)
        {
            unloadEvents();
            //Nouveau document vide
            Boolean reponseOK = !Openroject.isSaved && MessageBox.Show("Le présent document n'a pas été enregistré, voulez-vous l'enregistrer ?", "Enregistrement", MessageBoxButton.YesNo) == MessageBoxResult.Yes;
            Boolean valider = false;
            if (reponseOK)
            {
                mesObjets.SaveAllInDB(Grille_Principale);
                Image_SaveAs(null, null);
                valider = true;
            }
            else
            {
                if (MessageBox.Show("Attention, toutes les données seront perdue, êtes-vous sur de vouloir continuer ?", "Enregistrement", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                {
                    valider = true;
                }

            }

            if (valider)
            {
                Openroject.setActualProjectFIle(Openroject.getInternalBDDFIle());
                this.Title = "Merise Designer - " + Openroject.getActualProjectFIle() + " *";
                Openroject.isNew = true;
                Openroject.SetisCHanged(true);
                mesObjets.initAll(Grille_Principale);
                mesObjets.EraseAll(Grille_Principale, true);
                this.initGrillePrincipale();
                mesObjets.LoadingBDD(Grille_Principale);
                Openroject.isSaved = true;
                mesObjets.reLoadBackUp();
            }
            activate_MouseButtonDown();
        }
        //Export XML
        private void Image_Export(object sender, MouseButtonEventArgs e)
        {
            unloadEvents();
            //mesObjets.exportToXml();
            new Export(mesObjets).ShowDialog();
            activate_MouseButtonDown();

        }
        //Mode MCD/MLD
        private void Image_ModeMCD_MLD(object sender, MouseButtonEventArgs e)
        {
            lostFocusAll();
            mesObjets.changeMode();

            if (Mode.mode == Mode.MODE_MCD)
            {
                mld_bouton.Source = new BitmapImage(new Uri("/Resources/MCD.ico", UriKind.Relative));
                statusBar.Content = "mode MCD activé";

            }
            else
            {
                mld_bouton.Source = new BitmapImage(new Uri("/Resources/MLD.ico", UriKind.Relative));
                statusBar.Content = "mode MLD activé";

            }
        }
        //Imprimer
        private void Image_Print(object sender, MouseButtonEventArgs e)
        {
            unloadEvents();
            //Impression en image
            lostFocusAll();
            mesObjets.printToJPG(Grille_Principale, false);
            activate_MouseButtonDown();
        }

        //Annuler
        private void annuler_Click(object sender, RoutedEventArgs e)
        {
            mesObjets.back();
        }
        //Retablir
        private void retablir_Click(object sender, RoutedEventArgs e)
        {
            mesObjets.next();
        }

        //Ouvrir
        private void Image_OpenDocument(object sender, MouseButtonEventArgs e)
        {
            unloadEvents();
            if (!Openroject.isSaved && MessageBox.Show("Le présent document n'a pas été enregistré, voulez-vous l'enregistrer ?", "Enregistrement", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
            {
                Image_SaveAs(null, null);
            }
            this.OpenDocument(null, false);
        }
        //Enregistrer
        private void Image_Save(object sender, MouseButtonEventArgs e)
        {
            unloadEvents();
            if (Openroject.isNew)
            {
                Image_SaveAs(null, null);
            }
            else
            {
                mesObjets.SaveAllInDB(Grille_Principale);
                mesObjets.reLoadBackUp();
            }
            activate_MouseButtonDown();
        }
        //Enregistrer sous
        private void Image_SaveAs(object sender, MouseButtonEventArgs e)
        {
            unloadEvents();

            SaveFileDialog saveFileDialog1 = new SaveFileDialog();
            saveFileDialog1.Filter = "Merise designer|*" + Configuration.extensionFile + "";
            saveFileDialog1.Title = "Enregistrer une archive Merise designer sous *" + Configuration.extensionFile + "";
            saveFileDialog1.ShowDialog();

            if (saveFileDialog1.FileName != "")
            {
                mesObjets.SaveAllInDB(Grille_Principale);

                string path;
                if (Openroject.isNew)
                {
                    path = Openroject.getActualProjectFIle();
                }
                else
                {
                    path = Openroject.getActualProjectFIle();
                }

                string path2 = saveFileDialog1.FileName;

                try
                {

                    // Ensure that the target does not exist.
                    File.Delete(path2);

                    // Copy the file.
                    File.Copy(path, path2);
                    Console.WriteLine("{0} copié à {1}", path, path2);

                    // Try to copy the same file again, which should succeed.
                    File.Copy(path, path2, true);
                    Console.WriteLine("The second Copy operation succeeded, which was expected.");

                    Openroject.setActualProjectFIle(path2);
                    Openroject.isNew = false;
                    Openroject.SetisCHanged(true);
                    
                    this.initGrillePrincipale();
                    mesObjets.initAll(Grille_Principale);
                    mesObjets.LoadingBDD(Grille_Principale);
                    mesObjets.reLoadBackUp();
                    activate_MouseButtonDown();
                }

                catch
                {
                    Console.WriteLine("Erreur, impossible de copier le fichier.");
                }
                finally
                {
                    this.Title = "Merise Designer - " + Openroject.getActualProjectFIle();
                    activate_MouseButtonDown();
                }
            }
        }
        //Ajouter une entite
        private void tg_addEnite_Click(object sender, RoutedEventArgs e)
        {
            if (tg_addEntite.IsChecked == true)
            {
                activate_addEntite();
            }
            else
            {
                desactivate_addEntite();
            }
        }
        //Ajouter une association
        private void tg_AddAsso_Click(object sender, RoutedEventArgs e)
        {
            if (tg_AddAsso.IsChecked == true)
            {
                activate_AddAsso();
            }
            else
            {
                desactivate_AddAsso();
            }
        }
        //Ajouter une ligne
        private void tg_AddLine_Click(object sender, RoutedEventArgs e)
        {
            if (tg_AddLine.IsChecked == true)
            {
                activate_AddLine();
            }
            else
            {
                desactivate_AddLine();
            }
        }
        //Sipprimer un élément
        private void tg_Delete_Click(object sender, RoutedEventArgs e)
        {
            //if (tg_Delete.IsChecked == true)
            //{
            //    activate_Delete();
            //}
            //else
            //{
            //    desactivate_Delete();
            //}
            activate_Delete();
        }
        //Navigation
        private void tg_Naviguer_Click(object sender, RoutedEventArgs e)
        {
            if (tg_Naviguer.IsChecked == true)
            {
                activate_Nagivation();
            }
            else
            {
                desactivate_Navigation();
            }
        }
        //Selection
        private void nt_selection_Click(object sender, RoutedEventArgs e)
        {
            unloadEvents();
            activate_MouseButtonDown();
        }
        /*
        ////Copie la mise en forme
        //private void Image_CopieMiseEnForme(object sender, MouseButtonEventArgs e)
        //{
        //    ////Enlève les focus
        //    //lostFocusAll();

        //    ////initialise les variables
        //    //childEnt1 = null;
        //    //childEnt2 = null;

        //    ////Retire les évênements de base et implément les spécialisés
        //    //Grille_Principale.MouseLeftButtonDown -= new MouseButtonEventHandler(Grille_Principale_MouseLeftButtonDown);
        //    //myScroll.PreviewMouseLeftButtonDown += new MouseButtonEventHandler(Grille_Principale_CopieMiseEnforme);
        //    //lockMenu();
        //    //statusBar.Content = "Copie de mise en forme => Sélectionner un objet source";

        //}
        //void Grille_Principale_CopieMiseEnforme(object sender, MouseButtonEventArgs e)
        //{

        //    statusBar.Content = "Copie de mise en forme => Sélectionner l'objet de destination";
        //    //récupère l'élément à manipuler
        //    child.Clear();
        //    child.Add(CL_Graphique.GetActiveUIElement(e.GetPosition(Grille_Principale), Grille_Principale.Children));

        //    //exit de la fonction si aucun objet sélectionné
        //    if (child.First() == null) { return; }


        //    if (this.childEnt1 == null) this.childEnt1 = child.First();
        //    //mémorise 1 Entité ou Association
        //    this.childEnt2 = child.First();
        //    mesObjets.getFocus(child.First().Name, false);

        //    //Vérifie la sélection
        //    if (childEnt1 != null & childEnt2 != null & childEnt1!=childEnt2)
        //    {
        //        mesObjets.copyMiseEnforme(childEnt1.Name, childEnt2.Name);

        //        //enlève le focus 
        //        mesObjets.lostFocus(childEnt1.Name);
        //        mesObjets.lostFocus(childEnt2.Name);

        //        //Remet les évênements de base
        //        myScroll.PreviewMouseLeftButtonDown -= new MouseButtonEventHandler(Grille_Principale_CopieMiseEnforme);
        //        Grille_Principale.MouseLeftButtonDown += new MouseButtonEventHandler(Grille_Principale_MouseLeftButtonDown);
        //        unLockMenu();
        //        statusBar.Content = "Choisissez une opération à effectuer";
        //        child.Clear();
        //        childEnt1 = null;
        //        childEnt2 = null;
        //    }
        //}
        */

        //Editer
        private void Editer_Click(object sender, RoutedEventArgs e)
        {
            if (tg_Editer.IsChecked == true)
            {
                activate_Edit(false);
            }
            else
            {
                desactivate_Edit();
            }

        }

        //Convertir entité en association
        private void tg_convert_entityToAsso_Click(object sender, RoutedEventArgs e)
        {
            if (tg_convert_entityToAsso.IsChecked == true)
            {
                activate_convert_EntityToAsso();
            }
            else
            {
                desactivate_convert_EntityToAsso();
            }
        }
        //Convertir une association en entité
        private void tg_convert_AssoToEntity_Click(object sender, RoutedEventArgs e)
        {
            if (tg_convert_AssoToEntity.IsChecked == true)
            {
                activate_convert_AssoToEntity();
            }
            else
            {
                desactivate_convert_AssoToEntity();
            }

        }
        //Opérations succéssives
        private void tg_operationsSuccessives_Click(object sender, RoutedEventArgs e)
        {
            if (tg_operationsSuccessives.IsChecked == true)
            {
                unloadEvents();
                Configuration.mode_action_enchainees = true;
                img_operations_succ.Source = new BitmapImage(new Uri("/Resources/multiple.ico", UriKind.Relative));
                statusBar.Content = "Mode opérations succéssives : Activé";
                activate_MouseButtonDown();
            }
            else
            {
                unloadEvents();
                Configuration.mode_action_enchainees = false;
                img_operations_succ.Source = new BitmapImage(new Uri("/Resources/single.ico", UriKind.Relative));
                statusBar.Content = "Mode opérations succéssives : Désactivé";
                activate_MouseButtonDown();
            }
        }

        //Affichage par nom/code
        private void tg_nomCode_Click(object sender, RoutedEventArgs e)
        {
            if (tg_nomCode.IsChecked == true)
            {
                Configuration.affichache_noms_pasCode = false;
                img_nomCode.Source = new BitmapImage(new Uri("/Resources/code.ico", UriKind.Relative));
                statusBar.Content = "Affichage par CODE";
                mesObjets.updateMode();
            }
            else
            {
                Configuration.affichache_noms_pasCode = true;
                img_nomCode.Source = new BitmapImage(new Uri("/Resources/name.ico", UriKind.Relative));
                statusBar.Content = "Affichage par NOM";
                mesObjets.updateMode();
            }

        }

        #endregion

        #region Ouvrir
        public Boolean OpenDocument(String nameFile, Boolean ignoreIsNewIsSave)
        {
            Boolean result = false;
            String fileName = "";
            if (nameFile == null || nameFile == "")//ouverture depuis la boite de dialogue
            {

                OpenFileDialog browseFile = new OpenFileDialog();
                browseFile.Filter = "Merise designer Files (*" + Configuration.extensionFile + ")|*" + Configuration.extensionFile + "";
                browseFile.Title = "Choisir un fichier";
                browseFile.Multiselect = false;
                if (browseFile.ShowDialog() == false)
                {
                    this.activate_MouseButtonDown();
                    return false;
                }

                fileName = browseFile.FileName;
            }
            else //Ouverture automatique
            {
                if (!File.Exists(nameFile)) return false;
                if (System.IO.Path.GetExtension(nameFile) != Configuration.extensionFile) return false;
                fileName = nameFile;
            }

            try
            {
                if (Mode.mode == Mode.MODE_MLD) Image_ModeMCD_MLD(null, null);
                Openroject.setActualProjectFIle(fileName);
                if (!ignoreIsNewIsSave)
                {
                    Openroject.isNew = false;
                    Openroject.isSaved = true;
                    this.Title = "Merise Designer - " + Openroject.getActualProjectFIle();
                }
                Openroject.SetisCHanged(true);
                this.initGrillePrincipale();
                mesObjets.initAll(Grille_Principale);
                mesObjets.LoadingBDD(Grille_Principale);
                result = true;
                if (!ignoreIsNewIsSave) mesObjets.reLoadBackUp();
            }
            catch (Exception)
            {
                MessageBox.Show("Error opening file", "File Error", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                result = false;
            }
            finally
            {
                activate_MouseButtonDown();
            }
            return result;
        }
        #endregion

        #region Gestion du zoom
        //Gestion de la molette
        private void Zoom_Dezoom(object sender, MouseWheelEventArgs e)
        {
            myScroll.ScrollToVerticalOffset(myScroll.VerticalOffset - e.Delta / 3);

            if (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl))
            {
                if (e.Delta > 0)
                {
                    //up     
                    Zoom(e.GetPosition(Grille_Principale));
                }
                else
                {
                    //down
                    DeZoom(e.GetPosition(Grille_Principale));
                }
            }
        }

        //Opérations de Zoom et de Dézoom
        private void Zoom(Point position)
        {
            slider.Value += 0.1;
            Grille_Principale.LayoutTransform = new ScaleTransform(slider.Value, slider.Value, 0, 0);
        }
        private void DeZoom(Point position)
        {
            slider.Value -= 0.1;
            Grille_Principale.LayoutTransform = new ScaleTransform(slider.Value, slider.Value, position.X, position.Y);
        }
        #endregion

        #region Navigation
        Cursor _holdCursor = Cursors.Arrow;
        private void activate_Nagivation()
        {
            unloadEvents();
            Grille_Principale.MouseLeftButtonDown += new MouseButtonEventHandler(Navigate_MouseDown);
            statusBar.Content = "Navigation";

            Grille_Principale.Cursor = Cursors.Hand;
            tg_Naviguer.IsChecked = true;
            lockMenu();
        }
        private void desactivate_Navigation()
        {
            Grille_Principale.MouseLeftButtonDown -= new MouseButtonEventHandler(Navigate_MouseDown);
            activate_MouseButtonDown();
            Grille_Principale.Cursor = Cursors.Arrow;
            tg_Naviguer.IsChecked = false;
            unLockMenu();
            statusBar.Content = "Choisissez une opération";
        }
        Point scrollStartOffset;
        private void MiddleMouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.ChangedButton == MouseButton.Middle)
            {
                _holdCursor = Grille_Principale.Cursor;
                Grille_Principale.Cursor = Cursors.ScrollAll;
                Grille_Principale.MouseMove += new MouseEventHandler(Navigate_MouseMove);
                Grille_Principale.MouseUp += new MouseButtonEventHandler(Navigate_MouseMiddleButtonUp);

                _MousePosition = e.GetPosition(this);
                scrollStartOffset.X = myScroll.HorizontalOffset;
                scrollStartOffset.Y = myScroll.VerticalOffset;
            }
        }
        void Navigate_MouseDown(object sender, MouseEventArgs e)
        {
            Grille_Principale.Cursor = Cursors.ScrollAll;
            Grille_Principale.MouseMove += new MouseEventHandler(Navigate_MouseMove);
            Grille_Principale.MouseLeftButtonUp += new MouseButtonEventHandler(Navigate_MouseLeftButtonUp);

            _MousePosition = e.GetPosition(this);
            scrollStartOffset.X = myScroll.HorizontalOffset;
            scrollStartOffset.Y = myScroll.VerticalOffset;
        }
        void Navigate_MouseMove(object sender, MouseEventArgs e)
        {
            Console.WriteLine(e.GetPosition((UIElement)sender));
            // Get the new mouse position. 

            Point mouseDragCurrentPoint = e.GetPosition(this);

            // Determine the new amount to scroll. 
            Point delta = new Point(
                (mouseDragCurrentPoint.X > this._MousePosition.X) ?
                -(mouseDragCurrentPoint.X - this._MousePosition.X) :
                (this._MousePosition.X - mouseDragCurrentPoint.X),
                (mouseDragCurrentPoint.Y > this._MousePosition.Y) ?
                -(mouseDragCurrentPoint.Y - this._MousePosition.Y) :
                (this._MousePosition.Y - mouseDragCurrentPoint.Y));

            // Scroll to the new position. 
            myScroll.ScrollToHorizontalOffset(this.scrollStartOffset.X + delta.X);
            myScroll.ScrollToVerticalOffset(this.scrollStartOffset.Y + delta.Y);
        }
        void Navigate_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            Grille_Principale.Cursor = Cursors.Hand;
            Grille_Principale.MouseMove -= new MouseEventHandler(Navigate_MouseMove);
            Grille_Principale.MouseLeftButtonUp -= new MouseButtonEventHandler(Navigate_MouseLeftButtonUp);
            _MousePosition = e.GetPosition((UIElement)sender);
        }
        void Navigate_MouseMiddleButtonUp(object sender, MouseButtonEventArgs e)
        {
            Grille_Principale.MouseMove -= new MouseEventHandler(Navigate_MouseMove);
            Grille_Principale.MouseUp -= new MouseButtonEventHandler(Navigate_MouseMiddleButtonUp);
            _MousePosition = e.GetPosition((UIElement)sender);
            Grille_Principale.Cursor = _holdCursor;
        }
        #endregion

        private void About_Click(object sender, RoutedEventArgs e)
        {
            new About().ShowDialog();
        }





    }
}
